// pages/phoneNum/phoneNum.js
import {
  request
} from '../../request/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNum: '',
    num: '',
    numback: '',
    user: {},

    //设置初始的状态、包含字体、颜色、还有等待事件 > <
    sendTime: '获取验证码',
    sendColor: '#363636',
    snsMsgWait: 60
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user = typeof wx.getStorageSync('user') === 'string' ? JSON.parse(wx.getStorageSync('user')) : wx.getStorageSync('user');
    console.log(user);
    this.setData({
      user,
    });
  },
  //获取输入手机号绑定的值
  phone(e) {
    this.setData({
      phoneNum: e.detail.value
    })
  },
  //获取输入验证码的值
  Num(e) {
    this.setData({
      num: e.detail.value
    })
  },

  //点击获取验证码触发的函数
  getPhone(e) {
    let reg = /^1[3|4|5|7|8][0-9]{9}$/;
    if(this.data.phoneNum===''){
      wx.showToast({
        title: '请输入手机号',
        icon:'none'
      })
    }else if(!reg.test(this.data.phoneNum)){
      wx.showToast({
        title: '请输入正确的手机号',
        icon:'none'
      })
    }else{
      request({
        url:'user/random',
        data: {
          "user_phone": this.data.phoneNum
        },
      }).then((result) => {
        console.log(result);
        this.setData({
          numback: result.data
        })
      });
      var inter = setInterval(function () {
        this.setData({
          smsFlag: true,
          sendColor: '#cccccc',
          sendTime: this.data.snsMsgWait + 's后重发',
          snsMsgWait: this.data.snsMsgWait - 1
        });
        if (this.data.snsMsgWait < 0) {
          clearInterval(inter)
          this.setData({
            sendColor: '#363636',
            sendTime: '获取验证码',
            snsMsgWait: 60,
            smsFlag: false
          });
        }
      }.bind(this), 1000);
    }
  },



  //输入验证码之后点击确定按钮触发的函数
  goClick(e) {
    if (this.data.num == this.data.numback) {
      wx.showToast({
        title: '绑定成功',
        duration: 2000,
        icon: 'success'
      })
      request({
        url: 'user/getuser',
        data: {
          open_id: this.data.user.safetyInfo.open_id,
          user_phone: this.data.phoneNum
        },
      }).then((result) => {
        console.log(result);
        if (result.data.code == '0') {
          wx.setStorageSync('user', result.data.data);
          wx.reLaunch({
            url: '../../pages/index/index',
          });
        }
      })
    }
  },
})